const { ipcRenderer, BrowserWindow } = require("electron");
const { pinyin, html, customPinyin, clearCustomDict } = require("pinyin-pro");
const fs = require("fs");
const {
  handlePinyin,
  handleImport,
  handleDownload,
  handleEdit,
  loadCustomPinyin,
  replaceUnicode,
} = require("./js/index");
const package = require("./package.json");

let filec = [];
let directory = null;
let ul = document.querySelector(".files-list");
let fileDetail = document.querySelector(".file-detail");
let resultPreview = document.querySelector(".result-preview");
initDOM();
let watching = false;
ipcRenderer.on("getCustomFilePath", (event, data) => {
  let templateFilePath = data;
  if (templateFilePath) {
    try {
      fs.watch(window.templateFilePath, (eventType, fileName) => {
        if (watching && eventType !== "change") return;
        if (!singleFile) return;
        watching = true;
        makePreview(singleFile);
        clearCustomDict("pinyin");
        customPinyin(loadCustomPinyin(templateFilePath));
        setTimeout(() => {
          watching = false;
        }, 100);
      });
    } catch (e) {
      //TODO handle the exception
      console.log("e.message", e.message);
    }
  }
});
function initDOM() {
  //版本号
  document.querySelector(".version").innerText = "v" + package.version;

  //单词测试，监听单词测试文本的输入值
  document.querySelector(".test-text").addEventListener("change", (e) => {
    if (e.target.value.length < 9) {
      document.querySelector(".test-result").innerText = replaceUnicode(
        pinyin(e.target.value)
      );
      document.querySelector(".test-result").className = "test-result";
    } else {
      document.querySelector(".test-result").innerText = "最多允许输入8个汉字";
      document.querySelector(".test-result").className =
        "test-result test-warn";
    }
  });

  //文件上传，监听上传控件的输入值
  document.getElementById("fileInput").addEventListener("change", function () {
    handleReset();
    console.log("after handleReset");
    filec = document.getElementById("fileInput").files;
    filec = Array.from(filec);
    if (filec) {
      //文件已经选择好 下面可以写自己的上传代码了
      if (fileInterceptor(filec)) makeList();
    }

    document.getElementById("fileInput").value = ""; //重复选择同一文件受value影响不触发onchange事件
  });
}

let handleUpload = () => {
  document.getElementById("fileInput").click();
};
let handleConvert = () => {
  let span = document.querySelector(".progress-span");
  if (span !== null) span.remove();

  let link = document.querySelector(".open-link");
  if (link !== null) link.remove();
  // document.getElementById("fileOutput").click();
  // if(directory){
  handlePinyin(filec);
  // }
};
let handleReset = () => {
  while (ul.firstChild) {
    ul.removeChild(ul.lastChild);
  }
  while (fileDetail.firstChild) {
    fileDetail.removeChild(fileDetail.lastChild);
  }
  while (resultPreview.firstChild) {
    resultPreview.removeChild(resultPreview.lastChild);
  }
  let span = document.querySelector(".progress-span");
  if (span !== null) span.remove();

  let link = document.querySelector(".open-link");
  if (link !== null) link.remove();

  if (filec.length > 0) filec = [];
};
ul.addEventListener("click", (e) => {
  if (filec) {
    if (e.target.parentNode.tagName == "LI") {
      Array.from(document.querySelectorAll(".file-li")).forEach((liItem) => {
        liItem.className = "file-li";
      });
      e.target.parentNode.className = "file-li active-li";
      console.log("clickedFile", e.target.parentNode.innerText)
      let clickedFile = filec.find(
        (f) => f.name == e.target.parentNode.innerText.replace("名称: ", "").split("大小：")[0]
      );
      if (clickedFile) {
        while (fileDetail.firstChild) {
          fileDetail.removeChild(fileDetail.lastChild);
        }
        while (resultPreview.firstChild) {
          resultPreview.removeChild(resultPreview.lastChild);
        }
        makeDetail(clickedFile);
        makePreview(clickedFile);
      }
    }
  }
});

//文件属性字典
let dict = [
  ["name", "文件名称"],
  ["path", "文件路径"],
  ["lastModifiedDate", "上次修改时间"],
  ["size", "文件大小"],
  ["type", "文件类型"],
];
let enConvert = (en) => {
  let zh = dict.find((i) => i[0] == en);
  if (zh) zh = zh[1];
  return zh;
};

//文件类型、大小检测
let fileInterceptor = (files) => {
  let flag;
  let aintTxtCount = 0;

  files.forEach((file) => {
    if (file.type !== "text/plain") {
      aintTxtCount++;
    }
    if (file.size > 1024 * 1024 * 100) {
      alert("上传文件大小不得超100MB");
      flag = false;
    } else if (aintTxtCount !== 0) {
      flag = true;
    } else flag = true;
  });
  if (aintTxtCount !== 0 && flag)
    alert("提示：上传文件中存在非txt类型文件，若继续注音可能引发错误");
  return flag;
};

let singleFile = "";
//展示文件预览
let makePreview = (file) => {
  singleFile = file;
  resultPreview.innerHTML = "";

  let detailTip = document.createElement("div");
  detailTip.className = "detail-tip";
  detailTip.innerText = `注音结果预览`;

  let btn = document.createElement("button");
  btn.innerText = "复制";
  btn.style.marginLeft = '10px'
  detailTip.append(btn);

  btn.addEventListener("click", function (e) {
    const range = document.createRange();
    range.selectNode(resultPreview.lastChild);
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
  });

  let splitLine = document.createElement("div");
  splitLine.className = "split-line";
  resultPreview.appendChild(detailTip);
  resultPreview.appendChild(splitLine);

  const content = fs.readFileSync(file.path, "utf-8");
  let paras = content.split("\n");
  let htmlStr = "";
  for (let i = 0; i < paras.length; i++) {
    try {
      htmlStr +=
        "<br>" +
        html(paras[i], {
          customClassMap: {
            "red-item": paras[i]
              .split("")
              .filter(
                (p) => pinyin(p, { multiple: true, type: "array" }).length > 1
              ),
          },
        });
    } catch (error) {
      htmlStr += "err";
    }
  }
  let wrapper = document.createElement("div");
  wrapper.className="preview-wrapper"
  wrapper.innerHTML = htmlStr;
  resultPreview.appendChild(wrapper);
};

//展示文件详情
let makeDetail = (file) => {
  let detailTip = document.createElement("div");
  detailTip.className = "detail-tip";
  detailTip.innerText = `文件详细信息`;

  let splitLine = document.createElement("div");
  splitLine.className = "split-line";

  fileDetail.appendChild(detailTip);
  fileDetail.appendChild(splitLine);
  dict.forEach((i) => {
    for (let item in file) {
      if (i[0] == item) {
        let li = document.createElement("li");
        if (item == "lastModifiedDate")
          li.innerText = `${enConvert(item)}: ${file[item].toLocaleString()}`;
        else if (item == "size")
          li.innerText = `${enConvert(item)}: ${file[item]}字节`;
        else li.innerText = `${enConvert(item)}: ${file[item]}`;
        li.className = "file-li";
        // console.log('遍历item', item)
        fileDetail.appendChild(li);
      }
    }
  });

  //展示文件内容
  if (file.type !== "text/plain") return; //不是txt类型就不要加载内容文本了
  let li = document.createElement("li");
  let details = document.createElement("details");
  let summary = document.createElement("summary");
  let p = document.createElement("p");
  const content = fs.readFileSync(file.path, "utf-8");
  summary.innerText = "文件内容";
  p.innerText = content;
  p.className = "file-content";
  details.style.fontSize = "12px";
  details.appendChild(summary);
  details.appendChild(p);
  li.appendChild(details);
  fileDetail.appendChild(li);
};

//展示文件列表
let makeList = () => {
  filec.forEach((file, index) => {
    if (index < 1) {
      let splitLine = document.createElement("div");
      splitLine.className = "split-line";

      let countTip = document.createElement("div");
      countTip.className = "count-tip";
      countTip.innerText = `共 ${filec.length} 个文件`;

      ul.appendChild(countTip);
      ul.appendChild(splitLine);
    }
    let li = document.createElement("li");
    let span_name = document.createElement("span");
    let span_size = document.createElement("span");
    span_name.innerText = `名称: ${file.name}`;
    span_size.innerText = `大小：${
      file.size < 1024
        ? file.size + "B"
        : file.size < 1024 * 1024
        ? (file.size / 1024).toFixed(2) + "KB"
        : (file.size / (1024 * 1024)).toFixed(2) + "MB"
    }`;
    span_name.className = "file-span";
    span_size.className = "file-span";
    li.appendChild(span_name);
    li.appendChild(span_size);
    li.className = "file-li";
    ul.appendChild(li);
  });
};

let settingWin;
let handleSetting = () => {
  ipcRenderer.send("opensetting");
};
